package cn.sciento.farm.devicemanager;

import org.flywaydb.core.Flyway;
import org.flywaydb.core.api.FlywayException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;

@Component
public class FlywayCommandLineRunner implements CommandLineRunner {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Value("${sharding.jdbc.datasource.ds-0.url}")
    String url;

    @Value("${sharding.jdbc.datasource.ds-0.username}")
    String username;

    @Value("${sharding.jdbc.datasource.ds-0.password}")
    String password;

    @Override
    public void run(String... args) throws Exception {
        Flyway flyway = Flyway.configure().dataSource(url,username,password).load();
        try {
            flyway.migrate();
        }catch (FlywayException e){
            flyway.repair();
            throw e;
        }
        logger.info("迁移数据库成功");
    }
}
